<?php

namespace app\middleware;

use Closure;
use Exception;
use think\Request;
use think\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\model\User as UserModel;

class Auth
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 排除Account控制器的路由 从jwt.php读取排除配置
        $excludeRoutes = config('jwt.exclude');
        
        $currentRoute = strtolower($request->controller(true) . '/' . $request->action(true));
        
        // 如果是排除的路由，则直接通过
        if (in_array($currentRoute, $excludeRoutes)) {
            return $next($request);
        }
        
        // 获取请求头中的Authorization
        $authHeader = $request->header('Authorization');
        
        // 如果没有Authorization头，返回401错误
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return Response::create(['code' => 401, 'message' => '缺少有效的token', 'data' => []], 'json', 401);
        }
        
        // 提取token
        $token = substr($authHeader, 7); // 移除 'Bearer ' 前缀
        
        try {
            // 获取JWT配置
            $config = config('jwt');
            
            // 解码token
            $decoded = JWT::decode($token, new Key($config['secret'], $config['algorithm']));
            
            // 检查用户是否存在
            $user = (new UserModel)->where('id', $decoded->user_id)->find();
            if (!$user) {
                return Response::create(['code' => 401, 'message' => '用户不存在', 'data' => []], 'json', 401);
            }
            
            // 将用户信息添加到请求中，供后续使用
            $request->user = $user;
            
            // 继续处理请求
            return $next($request);
        } catch (Exception) {
            // token无效或已过期
            return Response::create(['code' => 401, 'message' => 'token无效或已过期', 'data' => []], 'json', 401);
        }
    }
}